package com.leesche.zcsp.node.web.controller.wechat.operate;

import com.leesche.zcsp.node.net.service.NetService;
import com.leesche.zcsp.node.pay.wecha.service.PayService;
import com.leesche.zcsp.node.utils.NetConfig;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.model.PubDevice;
import com.leesche.zcsp.node.web.model.PubDeviceDiscount;
import com.leesche.zcsp.node.web.service.*;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.Principal;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by kaider on 2016/10/18.
 */
@Controller
@RequestMapping("/wechat/operate/device")
public class WechatDeviceController {
    private final static Logger LOGGER = LoggerFactory.getLogger(WechatDeviceController.class);

    @Autowired
    private PrivilegeService privilegeService;
    @Autowired
    private PubDevicetypeService deviceTypeService;
    @Autowired
    private PubPlaceService placeService;
    @Autowired
    private PubDeviceService deviceService;
    @Autowired
    private PubDiscountService discountService;
    @Autowired
    private PubDeviceDiscountService deviceDiscountService;
    @Autowired
    private NetService netService;
    @Autowired
    private PayService payService;

    private final static String LIST_VIEW = "wechat/operate/device/listView";
    private final static String ADD_VIEW = "wechat/operate/device/addView";
    private final static String SHOW_VIEW = "wechat/operate/device/showView";
    private final static String SHOW_DISCOUNT_VIEW = "wechat/operate/device/discountView";
    private final static String SHOW_QR_VIEW = "wechat/operate/device/showQRView";
    private final static String FINANCE_MACHINE_VIEW = "wechat/operate/device/financeMachineView";

    /**
     * 设备列表
     * @param model
     * @return
     */
    @RequestMapping(value = "/listView", method = RequestMethod.GET)
    public String listView(Model model) {
        Long adminId = getAdminId();
        Integer userRoleType = privilegeService.getCurrentPrincipal().getNtype();

        QueryPubDeviceCondition condition = new QueryPubDeviceCondition();
        condition.setAdminId(adminId);
        List<InfoDeviceDto> deviceList = deviceService.findDeviceList(condition);

        List<InfoDeviceDto> onlineList = new ArrayList<InfoDeviceDto>();
        List<InfoDeviceDto> offlineList = new ArrayList<InfoDeviceDto>();

        for (InfoDeviceDto device : deviceList) {
            LOGGER.info("=======设备名称：" + device.getDeviceName() + "   imme：" + device.getImme());
            System.out.println("=======设备名称：" + device.getDeviceName() + "   imme：" + device.getImme());
            if (device.getState() == 1) {
                onlineList.add(device);
            } else {
                offlineList.add(device);
            }
        }

        model.addAttribute("onlineList", onlineList);
        model.addAttribute("offlineList", offlineList);

        String goView;

        switch (userRoleType) {
            //机修
            case 6:
                goView = FINANCE_MACHINE_VIEW;
                model.addAttribute("financeMachine", 0);
                break;
            //财务兼机修
            case 7:
                goView = FINANCE_MACHINE_VIEW;
                model.addAttribute("financeMachine", 1);
                break;
            default:
                goView = LIST_VIEW;
                model.addAttribute("cur", "device");
                break;
        }

        return goView;
    }

    /**
     * 增加设备界面
     * @param model
     * @return
     */
    @RequestMapping(value = "/addView/{shortCode}", method = RequestMethod.GET)
    public String addView(@PathVariable("shortCode") String shortCode,
                          Model model) {

        Long adminId = getAdminId();

        QueryPubDeviceCondition deviceCondition = new QueryPubDeviceCondition();
        deviceCondition.setDeviceshortcode(shortCode);

        PubDeviceDto device = deviceService.selectByCondition(deviceCondition);

        List<PubDevicetypeDto> deviceTypeList = deviceTypeService.findDeviceTypeList();

        QueryPubPlaceCondition placeCondition = new QueryPubPlaceCondition();
        placeCondition.setAdminId(adminId);
        List<PubPlaceDto> placeList = placeService.findPubPlaceList(placeCondition);

        QueryPubDiscountCondition discountCondition = new QueryPubDiscountCondition();
        discountCondition.setAdminId(adminId);
        List<PubDiscountDto> discountList = discountService.findDiscountList(discountCondition);

        model.addAttribute("deviceTypeList", deviceTypeList);
        model.addAttribute("placeList", placeList);
        model.addAttribute("device", device);
        model.addAttribute("discountList", discountList);
        return ADD_VIEW;
    }

    /**
     * 添加设备操作
     * @param device
     * @param discountIds 套餐id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public Map<String, Object> add(PubDevice device,
                                   @RequestParam("discountIds") Long[] discountIds) {
        try {
            //判断设备是否存在
            QueryPubDeviceCondition condition = new QueryPubDeviceCondition();
            condition.setDeviceshortcode(device.getDeviceshortcode());
            PubDeviceDto pubDeviceDto = deviceService.findByCondition(condition);
            if (pubDeviceDto == null) {
                return WebResult.success().info("未知设备").toMap();
            }
            //判断设备是否绑定过了
            if (StringUtils.isNotEmpty(pubDeviceDto.getMac())) {
                return WebResult.success().info("设备未绑定").toMap();
            }

            Long adminId = getAdminId();

            device.setAdminid(adminId);

            deviceService.updateByPrimaryKeySelective(device);

            LOGGER.info("设备名称：" + device.getDevicename() + "   imme：" + device.getImme());

            boolean flag = netService.isOnline(device.getImme());
            if (flag == true) {
                device.setIsonline(1);
                device.setState(1);
            } else {
                device.setIsonline(2);
                device.setState(2);
            }
            //判断设备的套餐是否存在

            Long deviceId = device.getDeviceid();

            addDeviceDiscount(discountIds, deviceId, adminId);

            return WebResult.success().info("操作成功").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure("添加设备错误").toMap();
        }
    }

    /**
     * 远程补币
     * @param deviceId
     * @param coin
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{deviceId}/addCoin", method = RequestMethod.POST)
    public Map<String, Object> addCoin(
            @PathVariable("deviceId") Long deviceId,
            @RequestParam("coin") Integer coin) {
        try {
            PubDevice device = deviceService.selectByPrimaryKey(deviceId);
            int deviceTypeId = Integer.parseInt(device.getDevicetypeid().toString());
            boolean flag = netService.sendClientBuy(device, 0, coin, NetConfig.PAYTYPE_GAMECOINBU, null);
            if (flag == true) {
                return WebResult.success().info("补币成功").toMap();
            } else {
                return WebResult.success().info("补币失败").toMap();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 单个设备具体信息
     * @return
     */
    @RequestMapping(value = "/{deviceId}/showView", method = RequestMethod.GET)
    public String showView(Model model, @PathVariable("deviceId") Long deviceId) {
        QueryPubDeviceCondition deviceCondition = new QueryPubDeviceCondition();
        deviceCondition.setDeviceId(deviceId);
        InfoDeviceDto device = deviceService.findInfoDevice(deviceCondition);

        model.addAttribute("device", device);
        return SHOW_VIEW;
    }

    /**
     * 修改设备状态
     * @param deviceId
     * @param isOnline
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{deviceId}/edit", method = RequestMethod.POST)
    public Map<String, Object> update(@PathVariable("deviceId") Long deviceId,
                                      Integer isOnline) {
        try {
            PubDevice device = deviceService.selectByPrimaryKey(deviceId);
            boolean flag = false;
            if (isOnline == 1) {
                flag = true;
            }
            int deviceTypeId = Integer.parseInt(device.getDevicetypeid().toString());

            Long adminId = getAdminId();

            netService.sendClientStartOrClose(device.getImme(), deviceTypeId, flag);
            device.setAdminid(adminId);
            device.setIsonline(isOnline);
            device.setState(isOnline);
            deviceService.updateByPrimaryKeySelective(device);
            return WebResult.success().info("操作成功").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 修改设备名称
     * @param deviceId
     * @param deviceName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{deviceId}/editName", method = RequestMethod.POST)
    public Map<String, Object> updateDeviceName(
            @PathVariable("deviceId") Long deviceId,
            @RequestParam("deviceName") String deviceName
    ) {
        try {
            Long adminId = getAdminId();

            PubDevice device = deviceService.selectByPrimaryKey(deviceId);
            device.setDevicename(deviceName);
            device.setAdminid(adminId);
            deviceService.updateByPrimaryKeySelective(device);
            return WebResult.success().info("操作成功").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设备套餐界面
     * @param deviceId
     * @param model
     * @return
     */
    @RequestMapping(value = "/{deviceId}/discountView", method = RequestMethod.GET)
    public String discountView(@PathVariable("deviceId") Long deviceId,
                               Model model) {
        Long adminId = getAdminId();

        QueryPubDiscountCondition discountCondition = new QueryPubDiscountCondition();
        discountCondition.setAdminId(adminId);
        List<PubDiscountDto> discounts = discountService.findDiscountList(discountCondition);

        QueryPubDeviceDiscountCondition condition = new QueryPubDeviceDiscountCondition();
        condition.setAdminId(adminId);
        condition.setDeviceId(deviceId);

        List<PubDiscountDto> discountList = new ArrayList<PubDiscountDto>();

        for (PubDiscountDto discountDto : discounts) {
            condition.setDiscountId(Long.valueOf(discountDto.getDiscountid()));
            Integer flag = deviceDiscountService.selectCheckDeviceDiscount(condition);
            if (flag == 1) {
                discountDto.setFlag(1);
            } else {
                discountDto.setFlag(0);
            }
            discountList.add(discountDto);
        }
        model.addAttribute("deviceId", deviceId);
        model.addAttribute("discountList", discountList);
        return SHOW_DISCOUNT_VIEW;
    }

    /**
     * 更新设备绑定的套餐
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{deviceId}/editDiscount", method = RequestMethod.POST)
    public Map<String, Object> editDiscount(
            @PathVariable("deviceId") Long deviceId,
            @RequestParam("discountIds") Long[] discountIds
    ) {
        try {
            Long adminId = getAdminId();

            QueryPubDeviceDiscountCondition condition = new QueryPubDeviceDiscountCondition();
            condition.setAdminId(adminId);
            condition.setDeviceId(deviceId);

            deviceDiscountService.deleteDeviceDiscount(condition);

            addDeviceDiscount(discountIds, deviceId, adminId);

            return WebResult.success().info("操作成功").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设备二维码界面
     * @param deviceId
     * @param model
     * @return
     */
    @RequestMapping(value = "/{deviceId}/qrCodeView", method = RequestMethod.GET)
    public String qrCodeView(
            @PathVariable("deviceId") Long deviceId,
            Model model
    ) {
        Long adminId = getAdminId();

        QueryPubDeviceCondition deviceCondition = new QueryPubDeviceCondition();
        deviceCondition.setDeviceId(deviceId);
        InfoDeviceDto deviceDto = deviceService.findInfoDevice(deviceCondition);

        QueryPubDeviceDiscountCondition condition = new QueryPubDeviceDiscountCondition();
        condition.setAdminId(adminId);
        condition.setDeviceId(deviceId);
        List<PubDeviceDiscountDto> list = deviceDiscountService.findListsByCondition(condition);
        if (list.size() < 1) {
            PubDeviceDiscountDto deviceDiscountDto = new PubDeviceDiscountDto();
            deviceDiscountDto.setPayUrl("http://m.leesche.cn/node/payinfo/" + deviceDto.getMac() + "/pay");
            model.addAttribute("device", deviceDiscountDto);
        }
        for (PubDeviceDiscountDto deviceDiscountDto : list) {
            String wechatUrl = payService.generateURL(deviceDiscountDto.getDeviceid(), deviceDiscountDto.getDiscountid(), "UTF-8");
            String alipayUrl = payService.generaterAlipay(deviceDiscountDto.getDeviceid(), deviceDiscountDto.getDiscountid());
            deviceDiscountDto.setAliPayUrl(alipayUrl);
            deviceDiscountDto.setWechatPayUrl(wechatUrl);
            deviceDiscountDto.setPayUrl("http://m.leesche.cn/node/payinfo/" + deviceDto.getMac() + "/pay");
        }

        model.addAttribute("list", list);
        return SHOW_QR_VIEW;
    }

    /**
     * 添加设备套餐
     * @param discountIds
     * @param deviceId
     * @param adminId
     */
    private void addDeviceDiscount(Long[] discountIds, Long deviceId, Long adminId) {
        for (Long discountId : discountIds) {
            PubDeviceDiscount deviceDiscount = new PubDeviceDiscount();
            deviceDiscount.setDiscountid(discountId);
            deviceDiscount.setDeviceid(deviceId);
            deviceDiscount.setAdminid(adminId);
            deviceDiscountService.insert(deviceDiscount);
        }
    }

    private Long getAdminId() {
        Principal principal = privilegeService.getCurrentPrincipal();
        Long adminId;
        if (principal.getParentid() == 1) {
            adminId = principal.getUserid();
        } else {
            adminId = principal.getParentid();
        }
        return adminId;
    }

}
